<template>
  <div v-if="vid">
    <el-alert
      class="u-m-b-10"
      description="获取当前最新的数据库创建sql，如果数据库表有更新的话，请点击同步最新SQL"
      title="说明"
      type="error"
    />
    <Codemirror
      v-model:value="code"
      v-loading="loading"
      :options="cmOptions"
      class="dk-code-mirror"
      style="height: 400px; overflow: auto"
    />
    <div v-if="sql.edit" style="text-align: center; font-size: 14px; color: #888; margin-top: 10px">当前SQL脚本已被修改</div>
    <div style="text-align: center; margin-top: 20px">
      <el-button type="primary" @click="saveInstallSql()">保存当前SQL</el-button>
      <el-button type="primary" @click="updateInstallSql()">同步最新SQL</el-button>
      <el-button type="danger" @click="downInstallSql()">下载install.sql</el-button>
    </div>
  </div>
</template>

<script>
import { getInstallSql, updateInstallSql, saveInstallSql } from '@/api/addons/version'
export default {
  name: 'InstallSql',
  components: {},
  props: {
    aid: {
      default: 0,
      type: [Number, String]
    },
    vid: {
      default: 0,
      type: [Number, String]
    },
    height: {
      default: 0,
      type: [Number]
    }
  },
  data() {
    return {
      sql: {},
      code: '',
      cmOptions: {
        tabSize: 4,
        mode: 'text/x-mysql',
        theme: 'monokai',
        lineNumbers: true,
        line: true
      },
      loading: true
    }
  },
  computed: {},
  mounted() {
    this.getInstallSql()
  },
  methods: {
    saveInstallSql() {
      // 执行前提示
      this.$confirm('如果当前版本不是最新版，将无法同步，确定要保存当前SQL脚本，', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          saveInstallSql(this.vid, this.code).then((res) => {
            this.$message.success('保存成功')
            this.sql = res.data
          })
        })
        .catch(() => {})
    },
    getInstallSql() {
      getInstallSql(this.vid)
        .then((res) => {
          this.sql = res.data
          this.code = res.data.sql
          this.loading = false
        })
        .catch((res) => {
          this.loading = false
          this.sql = {}
          this.code = ''
        })
    },
    updateInstallSql() {
      updateInstallSql(this.vid, this.code).then((res) => {
        this.$message.success('更新成功')
        this.getInstallSql()
        this.$emit('success')
      })
    },
    downInstallSql() {
      // 点击后下载为sql文件
      const blob = new Blob([this.code], { type: 'text/plain;charset=utf-8' })
      const downloadLink = document.createElement('a')
      downloadLink.href = window.URL.createObjectURL(blob)
      downloadLink.download = 'install.sql'
      document.body.appendChild(downloadLink)
      downloadLink.click()
      document.body.removeChild(downloadLink)
    }
  }
}
</script>

<style scoped lang="scss">
.dk-code-mirror {
  &::v-deep {
    .CodeMirror {
      height: 60vh;
    }
  }
}
</style>
